package concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * TODO 简单说明
 *
 * @author yangyang
 * @date 2017/7/26 19:23
 * @email kekecany@163.com
 */
class PrioritizedTask implements Runnable, Comparable<PrioritizedTask> {

    private Random random = new Random(47);
    private static int counter = 0;
    private final int id = counter++;
    private static List<PrioritizedTask> sequence = new ArrayList<>();
    private int priority;

    PrioritizedTask(int priority) {
        this.priority = priority;
        sequence.add(this);
    }

    @Override
    public int compareTo(PrioritizedTask arg) {
        return priority < arg.priority ? 1 : (priority > arg.priority ? -1 : 0);
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(random.nextInt(250));
        } catch (InterruptedException e) {
            // acceptable way to exit
        }
        System.out.println(this);
    }

    @Override
    public String toString() {
        return String.format("[%1$-3d]", priority) + " Task " + id;
    }

    String summary() {
        return "(" + priority + ": " + id + ")";
    }

    public static class EndSentinel extends PrioritizedTask implements Runnable {

        private ExecutorService executorService = Executors.newCachedThreadPool();

        EndSentinel(ExecutorService executorService) {
            super(-1); // lowest priority in this program
            this.executorService = executorService;
        }

        public void run() {
            int count = 0;
            for (PrioritizedTask task : sequence) {
                System.out.println(task.summary());
                if (++count % 5 == 0) {
                    System.out.println();
                }
            }
            System.out.println();
            System.out.println(this + " calling shutdownNow()");
            executorService.shutdownNow();
        }
    }
}

class PrioritizedTaskProducer implements Runnable {

    private Random random = new Random(47);
    private ExecutorService executorService;
    private Queue<Runnable> queue;

    PrioritizedTaskProducer(ExecutorService executorService, Queue<Runnable> queue) {
        this.executorService = executorService;
        this.queue = queue;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            queue.add(new PrioritizedTask(random.nextInt(10)));
            Thread.yield();
        }
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.MILLISECONDS.sleep(250);
//                System.out.println("******************");
                queue.add(new PrioritizedTask(10));
            }
            for (int i = 0; i < 10; i++) {
                queue.add(new PrioritizedTask(i));
            }
            queue.add(new PrioritizedTask.EndSentinel(executorService));
        } catch (InterruptedException e) {
            // acceptable way to exit
        }
        System.out.println("finished PrioritizedTaskProducer");
    }
}

class PrioritizedTaskConsumer implements Runnable {

    private PriorityBlockingQueue<Runnable> queue;

    PrioritizedTaskConsumer(PriorityBlockingQueue<Runnable> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                queue.take().run();
            }
        } catch (InterruptedException e) {
            // acceptable way to exit
        }
        System.out.println("finished PrioritizedTaskConsumer");
    }
}

public class PriorityBlockingQueueDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<>();
        executorService.execute(new PrioritizedTaskProducer(executorService, queue));
        executorService.execute(new PrioritizedTaskConsumer(queue));
    }
}